<template>
  <div class="admin-match">
    <el-card class="match-card" shadow="never">
      <template #header>
        <div class="card-header">
          <el-icon size="24" color="#2e7d32"><Setting /></el-icon>
          <span>高校管理端：匹配管理与三方确认</span>
        </div>
      </template>
      
      <el-alert 
        title="您可以查看所有申请数据，手动调整匹配关系，并进行三方确认。建议定期检查未匹配的申请，主动推荐合适的项目。" 
        type="info" 
        show-icon 
        class="info-alert"
      />
      
      <div class="stats-overview">
        <el-row :gutter="24">
          <el-col :span="6" v-for="stat in statsData" :key="stat.label">
            <div class="stat-card">
              <div class="stat-icon">
                <el-icon :size="24" :color="stat.color">{{ stat.icon }}</el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-number">{{ stat.value }}</div>
                <div class="stat-label">{{ stat.label }}</div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>

      <div class="filter-section">
        <el-form inline :model="filterForm">
          <el-form-item label="匹配状态">
            <el-select v-model="filterForm.status" clearable placeholder="全部状态">
              <el-option label="全部" value="" />
              <el-option label="待确认" value="pending" />
              <el-option label="已确认" value="confirmed" />
              <el-option label="已拒绝" value="rejected" />
            </el-select>
          </el-form-item>
          <el-form-item label="申请时间">
            <el-date-picker
              v-model="filterForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="学科分类">
            <el-select v-model="filterForm.discipline" clearable placeholder="全部学科">
              <el-option label="全部" value="" />
              <el-option v-for="d in disciplines" :key="d" :label="d" :value="d" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleFilter">
              <el-icon><Search /></el-icon>
              筛选
            </el-button>
            <el-button @click="handleResetFilter">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table 
        :data="tableData" 
        border 
        stripe
        class="match-table"
        v-loading="loading"
      >
        <el-table-column type="index" label="#" width="60" align="center" />
        <el-table-column prop="projectTitle" label="课题名称" min-width="250">
          <template #default="{ row }">
            <div class="project-info">
              <div class="project-title">{{ row.projectTitle }}</div>
              <div class="project-meta">
                <el-tag size="small" type="info">{{ row.applicantRole === 'supervisor' ? '导师' : '学生' }}</el-tag>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="enterpriseName" label="企业" width="160" align="center" />
        <el-table-column prop="applicantName" label="申请人" width="120" align="center" />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag 
              :type="getStatusType(row.status)" 
              size="small"
              effect="light"
            >
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="确认情况" min-width="220" align="center">
          <template #default="{ row }">
            <div class="confirmation-status">
              <div class="confirm-item">
                <el-tag 
                  :type="row.enterpriseConfirm ? 'success' : 'info'" 
                  size="small"
                  effect="light"
                >
                  企业
                </el-tag>
                <el-icon 
                  :color="row.enterpriseConfirm ? '#4caf50' : '#909399'"
                  :class="{ 'confirmed': row.enterpriseConfirm }"
                >
                  <Check v-if="row.enterpriseConfirm" />
                  <Clock v-else />
                </el-icon>
              </div>
              <div class="confirm-item">
                <el-tag 
                  :type="row.applicantConfirm ? 'success' : 'info'" 
                  size="small"
                  effect="light"
                >
                  申请方
                </el-tag>
                <el-icon 
                  :color="row.applicantConfirm ? '#4caf50' : '#909399'"
                  :class="{ 'confirmed': row.applicantConfirm }"
                >
                  <Check v-if="row.applicantConfirm" />
                  <Clock v-else />
                </el-icon>
              </div>
              <div class="confirm-item">
                <el-tag 
                  :type="row.adminConfirm ? 'success' : 'info'" 
                  size="small"
                  effect="light"
                >
                  管理端
                </el-tag>
                <el-icon 
                  :color="row.adminConfirm ? '#4caf50' : '#909399'"
                  :class="{ 'confirmed': row.adminConfirm }"
                >
                  <Check v-if="row.adminConfirm" />
                  <Clock v-else />
                </el-icon>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="申请时间" min-width="160" align="center">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" align="center" fixed="right">
          <template #default="{ row }">
            <el-space>
              <el-button 
                type="primary" 
                size="small" 
                @click="viewDetail(row)"
              >
                <el-icon><View /></el-icon>
                查看详情
              </el-button>
              <el-button 
                v-if="row.status === 'pending'"
                type="success" 
                size="small" 
                @click="confirmMatch(row)"
                :disabled="!canConfirm(row)"
              >
                <el-icon><Check /></el-icon>
                确认匹配
              </el-button>
              <el-button 
                v-if="row.status === 'pending'"
                type="danger" 
                size="small" 
                @click="rejectMatch(row)"
              >
                <el-icon><Close /></el-icon>
                拒绝
              </el-button>
              <el-button 
                v-if="row.status === 'pending'"
                type="warning" 
                size="small" 
                @click="recommendProject(row)"
              >
                <el-icon><Star /></el-icon>
                推荐项目
              </el-button>
            </el-space>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination 
          layout="total, sizes, prev, pager, next, jumper" 
          :total="total" 
          :page-sizes="[10, 20, 50]"
          :page-size="pageSize"
          :current-page="currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { mockMatchRecords, mockStatistics } from '@/services/mockData'
import { Setting, Search, Refresh, View, Check, Close, Star, Clock } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(mockMatchRecords.length)

const disciplines = ['人工智能', '新材料', '网络安全', '计算机视觉', '电子工程', '生物医学', '环境科学']

const filterForm = reactive({
  status: '',
  dateRange: [] as string[],
  discipline: ''
})

const statsData = [
  {
    label: '总申请数',
    value: mockStatistics.totalApplications,
    icon: 'Document',
    color: '#2e7d32'
  },
  {
    label: '待确认',
    value: mockMatchRecords.filter(r => r.status === 'pending').length,
    icon: 'Clock',
    color: '#ff9800'
  },
  {
    label: '已确认',
    value: mockMatchRecords.filter(r => r.status === 'confirmed').length,
    icon: 'Check',
    color: '#4caf50'
  },
  {
    label: '已拒绝',
    value: mockMatchRecords.filter(r => r.status === 'rejected').length,
    icon: 'Close',
    color: '#f44336'
  }
]

const tableData = computed(() => {
  let filtered = [...mockMatchRecords]
  
  if (filterForm.status) {
    filtered = filtered.filter(item => item.status === filterForm.status)
  }
  
  if (filterForm.dateRange && filterForm.dateRange.length === 2) {
    filtered = filtered.filter(item => {
      const date = new Date(item.createdAt)
      const start = new Date(filterForm.dateRange[0])
      const end = new Date(filterForm.dateRange[1])
      return date >= start && date <= end
    })
  }
  
  return filtered
})

const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: 'warning',
    confirmed: 'success',
    rejected: 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: '待确认',
    confirmed: '已确认',
    rejected: '已拒绝'
  }
  return statusMap[status] || status
}

const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

const canConfirm = (row: any) => {
  return row.enterpriseConfirm && row.applicantConfirm
}

const handleFilter = () => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
    ElMessage.success('筛选完成')
  }, 500)
}

const handleResetFilter = () => {
  filterForm.status = ''
  filterForm.dateRange = []
  filterForm.discipline = ''
  ElMessage.info('筛选条件已重置')
}

const viewDetail = (row: any) => {
  ElMessage.info(`查看详情：${row.projectTitle}`)
  // TODO: 跳转到详情页
}

const confirmMatch = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要确认"${row.projectTitle}"的匹配吗？`,
      '确认匹配',
      {
        confirmButtonText: '确定确认',
        cancelButtonText: '取消',
        type: 'success'
      }
    )
    
    ElMessage.success('匹配已确认')
    // TODO: 调用API确认匹配
  } catch {
    // 用户取消
  }
}

const rejectMatch = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要拒绝"${row.projectTitle}"的匹配吗？`,
      '拒绝匹配',
      {
        confirmButtonText: '确定拒绝',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    ElMessage.success('匹配已拒绝')
    // TODO: 调用API拒绝匹配
  } catch {
    // 用户取消
  }
}

const recommendProject = (row: any) => {
  ElMessage.info(`为"${row.applicantName}"推荐合适的项目`)
  // TODO: 实现推荐逻辑
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
}
</script>

<style scoped>
.admin-match {
  max-width: 1200px;
  margin: 0 auto;
}

.match-card {
  border-radius: 12px;
  border: 1px solid var(--border-color);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 18px;
  font-weight: 600;
  color: var(--primary-color);
}

.info-alert {
  margin-bottom: 24px;
}

.stats-overview {
  margin-bottom: 32px;
}

.stat-card {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  border: 1px solid var(--border-color);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background: rgba(46, 125, 50, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: 700;
  color: var(--primary-color);
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: var(--text-secondary);
  margin-top: 4px;
}

.filter-section {
  margin-bottom: 24px;
  padding: 20px;
  background: var(--background-secondary);
  border-radius: 8px;
}

.match-table {
  margin-bottom: 24px;
}

.project-info {
  text-align: left;
}

.project-title {
  font-weight: 500;
  color: var(--text-primary);
  margin-bottom: 4px;
}

.project-meta {
  display: flex;
  gap: 8px;
}

.confirmation-status {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.confirm-item {
  display: flex;
  align-items: center;
  gap: 8px;
  justify-content: center;
}

.confirm-item .el-icon {
  transition: all 0.3s ease;
}

.confirm-item .el-icon.confirmed {
  transform: scale(1.2);
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}

.el-table th {
  background-color: var(--background-secondary);
  color: var(--text-primary);
  font-weight: 600;
}

.el-table td {
  padding: 12px 0;
}

.el-button {
  border-radius: 6px;
}

.el-button .el-icon {
  margin-right: 4px;
}
</style>


